package com.shiwaixiangcun.customer.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import butterknife.ButterKnife
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.SurroundDetailAdapter
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.MerchDetailBean
import com.shiwaixiangcun.customer.glide.ImageDisplayUtil
import com.shiwaixiangcun.customer.interfaces.RequestPermissionType
import com.shiwaixiangcun.customer.presenter.impl.SurroundDetailImpl
import com.shiwaixiangcun.customer.ui.ISurroundDetailView
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut
import com.shiwaixiangcun.customer.utils.Utils
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.android.synthetic.main.activity_surround_detail.*
import kotlinx.android.synthetic.main.surround_detail_content.*
import kotlinx.android.synthetic.main.top_bar_white.*
import java.io.Serializable
import java.util.*

/**
 * @author Administrator
 */
class SurroundDetailActivity : BaseActivity(), View.OnClickListener, ISurroundDetailView {
    private var state: CollapsingToolbarLayoutState? = null

    private enum class CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    private var mPageName = ""
    private var merchId = ""
    private val mMerchList = ArrayList<MerchDetailBean.DataBean.AtlasBean>()
    private var surroundDetailAdapter: SurroundDetailAdapter? = null
    private var basicInformation: MerchDetailBean.DataBean.BasicInformationBean? = null
    private var phoneNumber = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_surround_detail)
        ButterKnife.bind(this)

        initViewAndEvent()
        initData()
    }

    @SuppressLint("WrongViewCast")
    private fun initViewAndEvent() {
        rlayout_phone.setOnClickListener(this)
        btn_phone.setOnClickListener(this)
        rl_check_more.setOnClickListener(this)
        back_left.setOnClickListener(this)
        appbar_layout.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            when {
                verticalOffset == 0 -> {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        state = CollapsingToolbarLayoutState.EXPANDED
                        tv_page_name.text = ""
                        tv_page_name.setTextColor(resources.getColor(R.color.ui_white))
                        back_left.setImageResource(R.mipmap.icon_back_lwhite)

                    }
                }
                (Math.abs(verticalOffset) >= appBarLayout.totalScrollRange) -> {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                        tv_page_name.text = mPageName
                        tv_page_name.setTextColor(resources.getColor(R.color.black_text_100))
                        back_left.setImageResource(R.mipmap.icon_back_green)
                        state = CollapsingToolbarLayoutState.COLLAPSED
                    }
                }
                else -> {
                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                    }
                    state = CollapsingToolbarLayoutState.INTERNEDIATE


                }
            }
        }
        surroundDetailAdapter = SurroundDetailAdapter(mMerchList)
        rv_surround_detail.adapter = surroundDetailAdapter
        rv_surround_detail.layoutManager = LinearLayoutManager(this)
        val divider = RecyclerViewDivider.Builder(this)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setMarginLeft(16f)
                .setMarginRight(16f)
                .setSize(0.5f)
                .setColorRes(R.color.color_divider_0_1)
                .build()
        rv_surround_detail.addItemDecoration(divider)
    }

    private fun initData() {

        val intent = intent
        merchId = intent.getStringExtra("merchId")
        val surroundDetail = SurroundDetailImpl(this)
        surroundDetail.setBgaAdpaterAndClick(this, merchId)


        surroundDetailAdapter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
            val atlasBean = surroundDetailAdapter!!.data[position]
            val atlasList = atlasBean.atlasList
            val title = atlasBean.title
            val imageList = ArrayList<String>()
            for (item in atlasList) {
                imageList.add(item.accessUrl)
            }
            val intent = Intent()
            intent.setClass(this@SurroundDetailActivity, ImageGalleryActivity::class.java)
            intent.putExtra("siteInfoList", imageList)
            intent.putExtra("imageTitle", title)
            startActivity(intent)
        }

    }

    override fun onClick(view: View) {
        val id = view.id
        when (id) {
            R.id.back_left -> finish()
            R.id.btn_phone -> if (Utils.isNotEmpty(btn_phone.text.toString().trim { it <= ' ' })) {
                callPhoneDialog(btn_phone!!.text.toString().trim { it <= ' ' })
            } else {
                Toast.makeText(this@SurroundDetailActivity, "没有商家电话", Toast.LENGTH_LONG).show()
            }
            R.id.rl_check_more -> {
                val intent = Intent(this@SurroundDetailActivity, ViewMoreActivity::class.java)
                intent.putExtra("articleId", merchId)
                startActivity(intent)
            }
            else -> {
            }
        }
    }

    override fun setDataResponse(result: MerchDetailBean) {
        iv_location_image.visibility = View.VISIBLE
        tv_detail_title.visibility = View.VISIBLE
        rl_check_more.visibility = View.VISIBLE
        tv_qualification.visibility = View.VISIBLE
        mMerchList.clear()
        basicInformation = result.data.basicInformation


        tv_detail_title.text = basicInformation?.name
        tv_detail_desc.text = basicInformation?.feature
        tv_location.text = basicInformation?.position
//        btn_phone.text = basicInformation!!.phone

        tv_food_title.text = basicInformation?.recommendStr

        if (Utils.isNotEmpty(basicInformation!!.description)) {
            ll_introduce_title.visibility = View.VISIBLE
            rl_check_more.visibility = View.VISIBLE
            tv_merch_detail_introduce.visibility = View.VISIBLE
            tv_merch_detail_introduce.text = basicInformation?.description
        } else {
            ll_introduce_title.visibility = View.GONE
            rl_check_more.visibility = View.GONE
            tv_merch_detail_introduce.text = ""
        }


        mPageName = basicInformation?.type.toString()
        btn_phone.text = basicInformation?.callButton
        phoneNumber = basicInformation?.callButton!!
        val atlas = result.data.atlas
        for (i in atlas.indices) {
            mMerchList.add(atlas[i])
        }
        surroundDetailAdapter!!.notifyDataSetChanged()
        if (atlas.size != 0) {
            tv_introduce_b.visibility = View.VISIBLE
        } else {
            tv_introduce_b.visibility = View.GONE
        }


        val certificate = result.data.certificate
        if (certificate.size > 0) {
            tv_qualification.visibility = View.VISIBLE
            getlt(certificate)
        } else {
            tv_qualification.visibility = View.GONE
        }
        val notEmpty = Utils.isNotEmpty(basicInformation!!.description)
        if (!notEmpty && certificate.size == 0) {
            tv_introduce_b.visibility = View.GONE
        } else {
            tv_introduce_b.visibility = View.VISIBLE
        }

        if (Utils.isNotEmpty(basicInformation!!.cover)) {
            ImageDisplayUtil.showImageView(mContext, basicInformation!!.cover, iv_detail_cover)
            Glide.with(mContext)
                    .load(basicInformation!!.cover)
                    .bitmapTransform(BlurTransformation(this, 20, 4))
                    .into(iv_blur)
        }


    }


    private fun getlt(certificates: List<MerchDetailBean.DataBean.CertificateBean>) {


        for (i in certificates.indices) {

            val view = LayoutInflater.from(this).inflate(R.layout.item_surround_detail_image, id_gallery, false)
            val ivCertificates = view.findViewById<ImageView>(R.id.iv_certificates)
            if (Utils.isNotEmpty(certificates[i].thumbImageURL)) {

                ImageDisplayUtil.showImageView(this, certificates[i].accessUrl, ivCertificates)
            }
            ivCertificates.setBackgroundColor(Color.parseColor("#332D3230"))
            view.setOnClickListener {
                val intent = Intent(this@SurroundDetailActivity, BigIamgeMerchanActivity::class.java)
                intent.putExtra("bigimagelist", certificates as Serializable)
                intent.putExtra("serid", i)
                startActivity(intent)
            }
            id_gallery.addView(view)
        }
    }


    /**
     * 拨打电话
     */
    private fun callPhoneDialog(phone: String) {
        val dialogLoginOut = DialogLoginOut(this@SurroundDetailActivity, R.layout.item_dialog_call_phone)
        dialogLoginOut.setTitle("是否要拨打此电话？")
        dialogLoginOut.setMessage(phone)
        dialogLoginOut.setYesOnclickListener("是", DialogLoginOut.OnPositiveOnclickListener {
            dialogLoginOut.dismiss()
            requestPermission(phone)

        })

        dialogLoginOut.setNoOnclickListener("否") { dialogLoginOut.dismiss() }
        dialogLoginOut.show()
    }

    private fun requestPermission(number: String?) {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE),
                        RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE)
                return
            } else {
                callPhone(number)
            }
        } else {
            callPhone(number)
        }
    }


    /**
     * 注册权限申请回调
     * @param requestCode 申请码
     * @param permissions 申请的权限
     * @param grantResults 结果
     */
    @Override
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callPhone(phoneNumber)
            } else {
                // Permission Denied
                Toast.makeText(this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

    /**
     * 拨号方法
     */
    @SuppressLint("MissingPermission")
    private fun callPhone(number: String?) {
        val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number))
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }
}
